<template>
  <div>
    <el-dialog
      :title="title"
      :visible="viewDialog"
      width="60%"
      :before-close="changeDialog"
    >
      <el-form
        :model="queryParams"
        :rules="queryParamsRules"
        ref="queryRef"
        label-width="150px"
        label-position="left"
      >
        <div v-if="status == 'add'">
          <el-row>
            <el-form-item prop="enterpriseId" label="所属油企名称">
              <el-select
                size="small"
                v-model="queryParams.enterpriseId"
                :clearable="true"
                filterable
                placeholder="请选择所属油企名称"
                @change="handleSelectChange"
                style="width: 300px"
              >
                <el-option
                  v-for="(item, index) in enterpriseList"
                  :key="index"
                  :value="item.enterpriseId"
                  :label="item.enterpriseName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item prop="stationId" label="分账出款商户名称">
              <el-select
                size="small"
                v-model="queryParams.stationId"
                :clearable="true"
                filterable
                placeholder="请选择分账出款商户名称"
                style="width: 300px"
              >
                <el-option
                  v-for="(item, index) in stationIdList"
                  :key="index"
                  :value="item.stationId"
                  :label="item.stationName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item prop="beginMmo" label="分账出款商户编号">
              <el-input
                style="width: 28%"
                maxlength="20"
                v-model.trim="queryParams.beginMmo"
                size="small"
              ></el-input>
            </el-form-item>
          </el-row>
        </div>
        <div v-if="status == 'edit'">
          <el-row>
            <el-form-item label="分账出款商户编号:">{{
              params.beginMmo
            }}</el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="分账出款商户名称:">
              {{ params.stationName }}
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="所属油企名称:">
              {{ params.enterpriseName }}
            </el-form-item>
          </el-row>
        </div>
        <el-row>
          <el-form-item prop="maxPercentage" label="最大分账比例(%)">
            <el-input
              style="width: 15%"
              v-model.trim="queryParams.maxPercentage"
              size="small"
            ></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <div>分账设置：</div>
      <el-table :data="dataList">
        <el-table-column
          property="mmoName"
          label="收款名称"
          width="150"
        ></el-table-column>
        <el-table-column
          property="mmo"
          label="收款账户"
          width="200"
        ></el-table-column>
        <el-table-column property="status" label="分账模式">
          <template slot-scope="{ row }">
            {{ row.status == 0 ? "比例" : "其他" }}
          </template>
        </el-table-column>
        <el-table-column property="percentage" label="分账值(%)">
          <template slot-scope="{ row }">
            {{ Number(row.percentage).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column
          property="divideTxt"
          label="分账描述"
        ></el-table-column>
        <af-table-column label="操作" align="left" width="200px">
          <!--fixed="right"-->
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleEdit(scope.row, scope.$index)"
              >修改</el-button
            >
            <el-button size="mini" type="text" @click="handleDel(scope.$index)"
              >删除</el-button
            >
          </template>
        </af-table-column>
      </el-table>
      <el-button type="text" @click="addPayee">添加收款方</el-button>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changeDialog">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :before-close="closeFormVisible"
      :title="title_1"
      :visible.sync="dialogFormVisible"
      width="30%"
    >
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item label="收款方名称" prop="mmoName">
          <el-input
            v-model="form.mmoName"
            maxlength="50"
            show-word-limit
            size="small"
          ></el-input>
        </el-form-item>
        <el-form-item label="收款账户" prop="mmo">
          <el-input
            v-model.trim="form.mmo"
            size="small"
            maxlength="20"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="分账模式" prop="status">
          <el-input size="small" v-model="form.status" disabled></el-input>
        </el-form-item>
        <el-form-item label="分账值" prop="percentage">
          <el-input size="small" maxlength="5" v-model.trim="form.percentage">
            <template slot="append">%</template></el-input
          >
        </el-form-item>
        <el-form-item label="分账描述">
          <el-input
            v-model="form.divideTxt"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            maxlength="200"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="closeFormVisible">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { enterpriseList } from "@/api/station/order";
import { listEnterpriseStation} from "@/api/dept";
import { editRule, addRule } from "@/api/billingAgreements/index.js";
import { cloneDeep } from "lodash";
export default {
  name: "AddOrEdit",
  props: {
    params: {
      default: () => {},
      type: Object,
    },
    viewDialog: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: "新增",
    },
    status: {
      type: String,
      default: "add",
    },
    statusType: {
      default: () => {},
      type: Object,
    },
  },
  data() {
    const validatePercentage = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("分账值不能为空"));
      }
      const regex = /^\d+(\.\d{1,2})?$/;
      if (!regex.test(value)) {
        return callback(new Error("只能输入数字且只能保留两位小数点"));
      }
      callback();
    };
    const validateMmo = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("收款账户不能为空"));
      }
      if (!/^[0-9]*$/.test(value)) {
        return callback(new Error("仅支持输入数字"));
      }
      if (
        value == this.queryParams?.beginMmo ||
        value == this.params?.beginMmo
      ) {
        return callback(new Error("收款账户不能与分账出款商户编号相同"));
      }
      callback();
    };
    const validateMaxPercentage = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("最大分账比例不能为空"));
      }
      const match = /^[1-9]\d?$|^100$/.test(value);
      if (!match) {
        return callback(new Error("只能输入1~100正整数"));
      }
      callback();
    };
    return {
      enterpriseList: [],
      dialogFormVisible: false,
      queryParams: {
        stationId: "",
      },
      queryParamsRules: {
        maxPercentage: [
          { required: true, validator: validateMaxPercentage, trigger: "blur" },
        ],
        beginMmo: [
          {
            required: true,
            message: "分账出款商户编号不能为空",
            trigger: "blur",
          },
        ],
        stationId: [
          {
            required: true,
            message: "分账出款商户名称不能为空",
            trigger: "change",
          },
        ],
        enterpriseId: [
          {
            required: true,
            message: "所属油企名称不能为空",
            trigger: "change",
          },
        ],
      },
      title_1: "新增收款人",
      form: {},
      rules: {
        mmoName: [
          { required: true, message: "收款方名称不能为空", trigger: "blur" },
        ],
        mmo: [{ required: true, validator: validateMmo, trigger: "blur" }],
        status: [
          { required: true, message: "分账模式不能为空", trigger: "blur" },
        ],
        percentage: [
          { required: true, validator: validatePercentage, trigger: "blur" },
        ],
      },
      dataList: [],
      currentIndex: "",
      isAllow: false, //判断最大分账值是否大于分账比列值
      stationIdList: [],
    };
  },
  watch: {
    viewDialog(val) {
      this.$refs["queryRef"]?.clearValidate();
      if (val && this.status == "edit") {
        this.dataList = cloneDeep(this.params.divideAccountsList);
        this.$set(this.queryParams, "maxPercentage", this.params.maxPercentage);
      }
    },
  },
  created() {
    this.getEnterpriseList()
  },
  methods: {
    // 查询油企
    async getEnterpriseList() {
      const res = await enterpriseList();
      this.enterpriseList = res.rows;
    },
    closeFormVisible() {
      this.$refs["formRef"].clearValidate();
      this.dialogFormVisible = false;
    },
    // 新增确认
    async submit() {
      if (this.dataList && !(this.dataList.length > 0)) {
        return this.$message.warning("请添加收款方");
      }
      let num =
        this.dataList &&
        this.dataList.reduce((sum, e) => sum + Number(e.percentage || 0), 0);
      if (this.queryParams.maxPercentage < num) {
        return this.$message.error(
          "目前分账收款方分账值总和已超出最大分账比例"
        );
      }
      await this.$refs["queryRef"].validate();
      const list = this.dataList.map((ele) => {
        if (ele.status == "比例") {
          return { ...ele, status: 0 };
        } else {
          return { ...ele };
        }
      });
      let data, res;
      if (this.status == "add") {
        data = { ...this.queryParams, divideAccountsList: list };
        res = await addRule(data);
      } else if (this.status == "edit") {
        data = {
          ...this.params,
          ...this.statusType,
          divideAccountsList: list,
          maxPercentage: this.queryParams.maxPercentage,
        };
        res = await editRule(data);
      }
      this.$message.success(res.msg);
      this.changeDialog();
    },
    // 关闭弹窗
    async changeDialog() {
      this.$refs["queryRef"].clearValidate();
      this.$emit("changeDialog");
      this.dataList = [];
      this.queryParams = {
        stationId: "",
      };
    },
    // 增加收款方
    addPayee() {
      this.form = {
        status: "比例",
      };
      this.dialogFormVisible = true;
      this.title_1 = "新增收款人";
    },
    // 修改收款方信息
    handleEdit(row, index) {
      this.dialogFormVisible = true;
      this.currentIndex = index;
      this.title_1 = "修改";
      this.form = cloneDeep(row);
      if (this.form.status == 0) this.form.status = "比例";
    },
    // 选中油企
    handleSelectChange(value) {
      this.stationIdList = [];
      this.queryParams.stationId = null;
      if (value) this.getStationList(value);
    },
    // 获取油站列表
    async getStationList(val) {
      const res = await listEnterpriseStation({ enterpriseId: val });
      this.stationIdList = res;
    },
    // 提交收款方信息
    async submitForm() {
      await this.$refs["formRef"].validate();
      if (this.form.status == "比例") this.form.status = 0;
      if (this.title_1 == "新增收款人") {
        this.dataList.push(this.form);
      } else {
        this.dataList.splice(this.currentIndex, 1, this.form);
        this.currentIndex = "";
      }
      console.log(this.dataList);
      this.dialogFormVisible = false;
    },
    // 删除
    async handleDel(index) {
      await this.$confirm("您确认删除吗？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      });
      this.dataList.splice(index, 1);
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-form-item {
  margin-bottom: 10px;
  font-weight: 500;
  color: #000;
}
::v-deep .el-form-item__error {
  line-height: 0.2;
}
::v-deep .el-input-group__append {
  background-color: transparent;
  // border-left: none;
}
// ::v-deep .el-form-item.is-error .el-input__inner {
//   border-right: none;
// }
</style>
